import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';

class TemperatureLineChart extends StatelessWidget {
  final List<double> temperatures;
  final List<String> hours;

  const TemperatureLineChart({
    Key? key,
    required this.temperatures,
    required this.hours,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final minTemp = (temperatures.reduce((a, b) => a < b ? a : b)).floor() - 2;
    final maxTemp = (temperatures.reduce((a, b) => a > b ? a : b)).ceil() + 2;
    return SizedBox(
      height: 180,
      child: LineChart(
        LineChartData(
          gridData: FlGridData(show: true),
          titlesData: FlTitlesData(
            leftTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 40,
                getTitlesWidget: (value, meta) {
                  return Text(
                    value.toInt().toString(),
                    style: const TextStyle(fontSize: 12),
                  );
                },
                interval: 2,
              ),
            ),
            bottomTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                getTitlesWidget: (value, meta) {
                  int idx = value.toInt();
                  if (idx % 3 == 0 && idx < hours.length) {
                    return Text(hours[idx],
                        style: const TextStyle(fontSize: 10));
                  }
                  return const SizedBox.shrink();
                },
                interval: 1,
                reservedSize: 28,
              ),
            ),
            rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
            topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)),
          ),
          borderData: FlBorderData(show: true),
          minX: 0,
          maxX: (temperatures.length - 1).toDouble(),
          minY: minTemp.toDouble(),
          maxY: maxTemp.toDouble(),
          lineBarsData: [
            LineChartBarData(
              spots: [
                for (int i = 0; i < temperatures.length; i++)
                  FlSpot(i.toDouble(), temperatures[i])
              ],
              isCurved: true,
              color: Colors.blue,
              barWidth: 3,
              dotData: FlDotData(show: false),
            ),
          ],
        ),
      ),
    );
  }
}
